package com.contract.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.contract.mapper.BizContractInfoMapper;
import com.contract.mapper.BizFileMapper;
import com.contract.mapper.SysRegisterMapper;
import com.contract.mapper.SysUserMapper;
import com.contract.pojo.bo.SysUser;
import com.contract.pojo.input.UserQueryInput;
import com.contract.pojo.output.JsonResult;
import com.contract.pojo.output.PageOutput;
import com.contract.pojo.output.UserOutput;
import com.contract.service.common.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * 用户service
 *
 * @author liw
 * @version 1.0
 * @date 2022/6/13 11:10
 */
@Slf4j
@Service
public class SysUserService extends BaseService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRegisterMapper sysRegisterMapper;

    @Autowired
    private BizContractInfoMapper bizContractInfoMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private FileService fileService;

    @Autowired
    private BizFileMapper bizFileMapper;

    /**
     * 查询列表
     *
     * @param vo 查询条件
     * @return data
     */
    public JsonResult<PageOutput<UserOutput>> queryList(UserQueryInput vo) {
        LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();
        PageOutput.Node<SysUser, UserOutput> node = new PageOutput.Node<SysUser, UserOutput>()
                .setFun(dtoConverter::userBo2Vo);
        if (!ObjectUtils.isEmpty(vo.getUserName())) {
            qw.like(SysUser::getUserName, vo.getUserName());
        }
        if (!ObjectUtils.isEmpty(vo.getState())) {
            qw.eq(SysUser::getState, vo.getState());
        }
        qw.orderByDesc(SysUser::getUpdateTime);
        if (Boolean.TRUE.equals(vo.getEnable())) {
            Page<SysUser> objectPage = new Page<>(vo.getPageNo(), vo.getPageSize());
            objectPage.setOptimizeCountSql(false);
            node.setPage(sysUserMapper.selectPage(objectPage, qw));
        } else {
            node.setList(sysUserMapper.selectList(qw));
        }
        return JsonResult.success(PageOutput.page(node));
    }

    /**
     * 查询
     *
     * @return data
     */
    public JsonResult<UserOutput> queryInfo(Long id) {
        SysUser user = sysUserMapper.selectById(id);
        UserOutput userOutput = dtoConverter.userBo2Vo(user);
        return JsonResult.success(userOutput);
    }

    /**
     * 查询
     *
     * @return data
     */
    public JsonResult<Long> deleteUser(Long id) {
        sysUserMapper.deleteById(id);
        sysRegisterMapper.deleteById(id);
        return JsonResult.success(id);
    }

}
